<template>
  <div class="login">
    <div class="left"></div>
    <div class="loginContainer">
      <h1 class="title">亿锋管理系统</h1>
      <el-form :model="loginForm"
               :rules="rules"
               ref="loginForm"
               label-width="100px"
               class="demo-loginForm">
        <el-form-item label="用户名"
                      prop="username">
          <el-input type="text"
                    v-model="loginForm.username"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码"
                      prop="password">
          <el-input type="password"
                    v-model="loginForm.password"
                    autocomplete="off"></el-input>
        </el-form-item>
        <!-- 验证码 -->
        <el-form-item label="验证码"
                      prop="captcha">
          <el-input type="text"
                    class="captcha"
                    v-model="loginForm.captcha"
                    autocomplete="off"
                    @keydown.native.enter="submitForm('loginForm')"></el-input>
          <span class="captcha-svg"
                @click="refreshCaptcha"
                v-html="captchaSvg">12321312</span>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     @click="submitForm('loginForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
    <video class="bg_video"
           muted
           src="../../assets/video/bg_video.mp4"
           autoplay
           loop
           preload="auto"></video>
  </div>
</template>
<script>
  import allRoutes from "@/router/allRoutes";
  import recursionRoutes from "@/utils/recursionRoutes";
  import { getCaptcha, verifyCaptcha, login, getMenuList } from "@/api";
  //登入逻辑的实现
  //1.收集用户输入的username&password传递给后端

  //2.登入通过后,将后端返回的token存到本地,跳转到主页

  //3.每次请求的时候,携带token到请求头authorization

  //4.展示token校验正确的数据

  //5.校验不通过,跳转到登入页
  export default {
    data() {
      // 校验用户名
      var validateUsername = (rule, value, callback) => {
        // 用户名正则，4到16位（字母，数字，下划线，减号）
        // var uPattern = /^[a-zA-Z0-9_-]{4,16}$/
        if (!value) {
          // console.log(123);
          callback(new Error("请输入用户名4到16位"));
        } else {
          callback();
        }
      };
      // 校验用户密码
      var validatePassword = (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入密码"));
        } else {
          callback();
        }
      };
      //校验验证码
      var validateCaptcha = (rule, value, callback) => {
        if (value === "" || value.length !== 5) {
          callback(new Error("请输入验证码"));
        } else {
          callback();
        }
      };
      return {
        captchaSvg: "", //从服务器获取下来的验证码svg结构
        loginForm: {
          username: "",
          password: "",
          captcha: "",
        },
        rules: {
          username: [{ validator: validateUsername, trigger: "blur" }],
          password: [{ validator: validatePassword, trigger: "blur" }],
          captcha: [{ validator: validateCaptcha, trigger: "blur" }],
        },
      };
    },
    mounted() {
      //获取验证码
      this.getCaptchaCode();
    },
    methods: {
      refreshCaptcha() {
        this.getCaptchaCode();
      },
      //获取验证码
      getCaptchaCode() {
        //调用http方法
        getCaptcha().then((res) => {
          // console.log(res);
          this.captchaSvg = res.data.img;
          // console.log(this.captchaSvg);
        });
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //代表本地校验通过
            const loading = this.$loading({
              lock: true,
              text: "正在登入...",
              spinner: "el-icon-loading",
              background: "rgba(0, 0, 0, 0.7)",
            });
            //先验证验证码是否正确
            verifyCaptcha(this.loginForm.captcha).then((res) => {
              if (res.data.state) {
                //打开加载动画
                //正确=>校验用户名密码
                let { username, password } = this.loginForm;
                login(username, password).then((res) => {

                  // console.log(loading);
                  if (res.data.state) {
                    //用户名密码正确
                    let { permission, token, userInfo } = res.data;
                    //将token储存到本地
                    localStorage.setItem("yf-token", token);

                    //获取用于的权限菜单
                    this.$store.dispatch("FETCH_MENULIST").then(() => {
                      // console.log(11111);
                    });

                    //跳转到首页
                    this.$router.push("/");
                    loading.close();
                  } else {
                    //用户名密码错误
                    this.$message.error("用户名密码错误");
                  }
                });
              } else {
                //错误=>返回错误信息
                // console.log(res);
                this.getCaptchaCode();
                this.$message.error("验证码错了哦，请重新输入");
                loading.close();
              }
            });
          } else {
            console.log("error submit!!");
            loading.close();
            return false;
          }
        });
      },
    },
  };
</script>
<style scoped lang="scss">
  .captcha {
    width: 100px;
    vertical-align: top;
    ::v-deep .el-input__inner {
      height: 45px;
      border-radius: 5px 0 0 5px;
      border: 0;
      font-size: 18px;
    }
  }
  svg path {
    stroke: red;
  }
  .captcha-svg {
    background: #fff;
    display: inline-block;
    height: 45px;
    width: 150px;
    text-align: center;
    cursor: pointer;
    border: 0;
    border-radius: 0px 5px 5px 0;
  }
  //登入
  .login {
    height: 100%;
    width: 100%;
    background: url("../../assets/imgs/bg.jpg");
    overflow: hidden;
  }

  .loginContainer {
    position: relative;
    z-index: 9;
    width: 25rem;
    height: 30.47619048rem;
    position: absolute;
    top: 50%;
    left: 75%;
    /* -webkit-transform: translate(-50%, -50%); */
    transform: translate(-50%, -50%);
    border-radius: 11px;
    background: rgba(83, 107, 182, 0.46);
    background: rgba(0, 0, 0, 0.2);
    text-align: center;
    .title {
      color: #fff;
      margin-top: 100px;
      margin-bottom: 50px;
    }
    .el-button.el-button--primary {
      width: 100%;
      background: linear-gradient(90deg, #1596fb, #002dff);
    }
    .bg_video {
      display: block;
      margin: auto;
      min-width: 100%;
      min-height: 100%;
      width: auto;
      height: auto;
      position: absolute;
      top: 0;
      left: 0;
      opacity: 0.5;
    }
    ::v-deep .el-form-item__label {
      color: #fff;
    }
  }
  .left {
    width: 50%;
    height: 100%;
    background-image: url("../../assets/imgs/bg2.png");
    background-repeat: no-repeat;
    background-size: 50%;
    // float: left;
    position: absolute;
    opacity: 0.7;
    background-position: 60% 65%;
  }
  .el-form.demo-loginForm {
    padding: 0 50px 0 0;
  }
</style>
